package com.lhc.service.impl;

import com.lhc.dao.ItemDOMapper;
import com.lhc.dao.ItemStockDOMapper;
import com.lhc.dataObject.ItemDO;
import com.lhc.dataObject.ItemStockDO;
import com.lhc.error.BusniessException;
import com.lhc.error.EmBussinessError;
import com.lhc.service.ItemService;
import com.lhc.service.model.ItemModel;
import com.lhc.validator.ValidationImpl;
import com.lhc.validator.ValidationResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.naming.ldap.PagedResultsControl;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ValidationImpl validation;

    @Autowired
    private ItemDOMapper itemDOMapper;

    @Autowired
    private ItemStockDOMapper itemStockDOMapper;
    /*
    创建商品，先在itemservice写方法，之后在impl写实现。
    1.入库前的校验入参
    2，转化itemmodel变为dataobject。
    3.写入数据库
    4.返回创建完成的对象。（创建完对象要返回实体，要上游知道我们创建的是什么样的对象）
     尽可能让controller层简单，service层复杂。
     */

    @Override
    @Transactional
    public ItemModel createItem(ItemModel itemModel) throws BusniessException {
        //校验入参
        ValidationResult result = validation.validate(itemModel);
        if (result.isHasErrors()) {
            throw new BusniessException(EmBussinessError.PARAMETER_VALIDATION_ERROR, result.getErrMsg());
        }
        //转化itemmodel变为dataobject。
        ItemDO itemDO = this.convertFromItemModel(itemModel);
        //写入数据库
        itemDOMapper.insertSelective(itemDO);
        //获取插入后的主键id值
        itemModel.setId(itemDO.getId());
        //转化model->itemStockDO
        ItemStockDO itemStockDO = this.convertFromItemStockModel(itemModel);
        //写入数据库
        itemStockDOMapper.insertSelective(itemStockDO);
        //根据id获取
        ItemModel Model = this.getItemById(itemModel.getId());

        // 返回创建完成的对象。（创建完对象要返回实体，要上游知道我们创建的是什么样的对象）尽可能让controller层简单，service层复杂。

        return Model;
    }

    @Override
    public List<ItemModel> listItem() {
        List<ItemDO> itemDOList = itemDOMapper.selectList();
        List<ItemModel> itemModelList = itemDOList.stream().map(itemDO -> {
                    ItemStockDO itemStockDO = itemStockDOMapper.selectByItemId(itemDO.getId());
                    ItemModel itemModel = this.convertFromDataObjectDo(itemDO, itemStockDO);
                    return itemModel;
                }
        ).collect(Collectors.toList());
        return itemModelList;
    }

    @Override
    public ItemModel getItemById(Integer id) {
        //根据id获取商品do
        ItemDO itemDO = itemDOMapper.selectByPrimaryKey(id);
        if (itemDO == null) {
            return null;
        }
        //根据商品id获取库存信息
        ItemStockDO itemStockDO = itemStockDOMapper.selectByItemId(itemDO.getId());
        //将itemdo -> ItemModel
        return this.convertFromDataObjectDo(itemDO, itemStockDO);

    }

    @Override
    @Transactional
    public boolean decreaseStock(Integer itemId,Integer account) {
        int effectRow = itemStockDOMapper.decreaseStock(itemId, account);
        if (effectRow > 0){
            //减库存成功！
            return true;
        }
        return false;
    }

    private ItemModel convertFromDataObjectDo(ItemDO itemDO, ItemStockDO itemStockDO) {
        ItemModel itemModel = new ItemModel();
        BeanUtils.copyProperties(itemDO, itemModel);
        itemModel.setStock(itemStockDO.getStock());
        itemModel.setPrice(new BigDecimal(itemDO.getPrice()));
        return itemModel;
    }

    private ItemDO convertFromItemModel(ItemModel itemModel) {
        if (itemModel == null) {
            return null;
        }
        ItemDO itemDO = new ItemDO();
        BeanUtils.copyProperties(itemModel, itemDO);
        itemDO.setPrice(itemModel.getPrice().doubleValue());
        return itemDO;

    }

    private ItemStockDO convertFromItemStockModel(ItemModel itemModel) {
        ItemStockDO itemStockDO = new ItemStockDO();
        if (itemModel == null) {
            return null;
        }
        itemStockDO.setItemId(itemModel.getId());
        itemStockDO.setStock(itemModel.getStock());
        return itemStockDO;
    }
}
